import React, { PureComponent } from "react";
import { View, StyleSheet, SafeAreaView, Text, DeviceEventEmitter, ToastAndroid, Alert } from "react-native";
import { TText } from "../common/Widgets/WidgetDefault";
import { Button, Icon, Overlay } from "react-native-tengits-elements";
import Swiper from "react-native-tengits-swiper";
import DataCenter from "../logic/DataCenter";
import { OverlayGateSelectList } from "./Components/GateSelectList";
import { scaleSize } from "../common/Utils/ToolUtils";
import { Colors, FontSize } from "../common/Theme/TTheme";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import DeviceInfo from 'react-native-device-info';
import { HoleType, holeType2Name, onlineStatus } from "../logic/LogicConstant";
import LoadingUtil from "../common/Utils/LoadingUtil";
import NetInfo from "@react-native-community/netinfo";
import { getAppVersion } from "../Http/HttpService";
import { versionCompare } from "../common/Utils/Utils";
import UpgradeLibrary from "../libs/Upgrade";
import UICommandExecute from "../logic/UICommandExecute";
import { OnlineStatusComponent } from "./Components/SubItemComponent";
import SerialPortManager from "../logic/SerialPortManager";
import {LightMode} from "../libs/SerialCommon";

export default class DeviceInfoPage extends React.PureComponent {
    constructor(props) {
        super(props);
        let data = [DataCenter.getLocalCabinetData(), ...DataCenter.getColonyExceptLocalCabinetData()];
        this.state = {
            index:0,
            colonyCabinet: data,
            selectDeviceVisible: false,
            lightMode: SerialPortManager.getLightMode()?.name,
            online: data[0].onlineStatus,
        };
    }

    componentDidMount() {
        this.localCabinetListener = DeviceEventEmitter.addListener("localCabinet", this.updateState.bind(this));
        this.colonyCabinetListener = DeviceEventEmitter.addListener("colonyCabinet", this.updateState.bind(this));
        this.lightModeListener = DeviceEventEmitter.addListener("lightMode", ()=>{
            this.setState({
                lightMode: SerialPortManager.getLightMode()?.name,
            });
        });
    }

    updateState() {
        let data = [DataCenter.getLocalCabinetData(), ...DataCenter.getColonyExceptLocalCabinetData()];
        let lastIndex = this.state.index;
        if(lastIndex >= data.length){
            lastIndex = Math.min(lastIndex, data.length - 1);
        }
        this.setState({
            colonyCabinet: data,
            index: lastIndex,
            online: data[lastIndex].onlineStatus,
        });
    }

    componentWillUnmount() {
        this.localCabinetListener.remove();
        this.colonyCabinetListener.remove();
        this.lightModeListener.remove();
    }

    getHeadTitle = ()=>{
        const{index, colonyCabinet} = this.state;
        let baseName = DataCenter.getTunnleBaseInfo();
        return baseName + (colonyCabinet[index]?.gateName ? colonyCabinet[index]?.gateName : "");
    }

    renderHeader() {
        const{index, colonyCabinet, online} = this.state;
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                {index > 0 ? <Button 
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        const{index} = this.state;
                        let ret = Math.max(0, index-1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                }}/>: null}
                <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                {index == 0 ? <View style={{alignItems:'center', justifyContent:'center', marginLeft: scaleSize(20), width:scaleSize(100), borderRadius:scaleSize(6), height:scaleSize(40), backgroundColor: Colors.calm_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"本柜"}</Text>
                    </View> : <View style={{alignItems:'center', justifyContent:'center', borderRadius:scaleSize(6), marginLeft: scaleSize(20), width:scaleSize(100), height:scaleSize(40), backgroundColor: "#FFAB2D"}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"非本柜"}</Text>
                    </View>}
                {online == onlineStatus.OFFLINE ?  <OnlineStatusComponent isOnline={false} containerStyle={{marginLeft: scaleSize(12)}}/> : null}
                </View>
                {index < ((colonyCabinet||[]).length - 1) ? <Button
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        const{index} = this.state;
                        let ret = Math.min((colonyCabinet||[]).length - 1, index+1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                    }}
                    /> : null}
            </View>
            <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='sync-alt' type='MaterialIcons' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.setState({selectDeviceVisible: true});
                }}/>
        </View>
    }

    toggleOverlay = (key) => {
        if(key == "GateSelect") {
            this.setState({selectDeviceVisible: false});
        } 
    }

    onSure = (key, params) => {
        const{index, colonyCabinet} = this.state;
        if(key == "GateSelect") {
            this.setState({index: params},()=>{
                this.setState({selectDeviceVisible: false,
                    online: colonyCabinet[params].onlineStatus,
                    });
            });
        } 
    }

    setLightMode = (value) => {
        this.setState({lightMode: value});
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Main');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}} 
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}} 
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}} 
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice');
                }}/>
            </View>
    }

    render() {
        const{index, colonyCabinet, selectDeviceVisible, lightMode} = this.state;
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                <Swiper index={index} showsButtons={false} 
                    loop={false} autoplay={false} 
                    showsPagination={false} scrollEnabled={false}>
                    {(colonyCabinet||[]).map((item, index)=>{
                        return <View key={"dv_"+index} style={{flex:1, paddingVertical:scaleSize(30), paddingHorizontal: scaleSize(46), backgroundColor: index == 0 ? Colors.page_bg_color : Colors.page_bg_color1}}>
                            <SubDeviceInfoPage  data={item} index={index} lightMode={lightMode} setLight={this.setLightMode}
                            key={index}/>
                            </View>
                    })}
                </Swiper>
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
                <Overlay overlayStyle={{padding:0}} isVisible={selectDeviceVisible} onBackdropPress={()=>{this.toggleOverlay("GateSelect")}} fullScreen>
                    <OverlayGateSelectList data={colonyCabinet} 
                    index={index}
                    localIndex={0}
                    toggleOverlay={this.toggleOverlay} onSure={this.onSure}/>
                </Overlay>
        </SafeAreaView>
    }
}
const SubInfoItem = (props) => {
    const{title, value} = props;
    return (<View style={styles.tipContainer}>
            <View >
            <Text style={{width:scaleSize(200), textAlign:'right', fontSize: FontSize.h3_font, color: Colors.text2_color}}>{`${title}`}</Text>
            </View>
            <View style={{marginLeft:scaleSize(20)}}>
            <Text style={{fontSize: FontSize.h3_font, color: Colors.text1_color}}>{value ? `${value}` : "--"}</Text>
            </View>
    </View>)
}
const SubDeviceInfoPage = (props) => {
    return <View style={{flexDirection:'column', justifyContent:'center'}}>
            <View style={styles.cardContainer}>
                <View style={{flex:1,}}>
                    <SubInfoItem title={"隧道:"} value={`${DataCenter.tunnelName}`}/>
                    <SubInfoItem title={"桩号:"} value={`${props.data.portalNumber||"--"}`}/>
                    <SubInfoItem title={"幅别:"} value={`${holeType2Name(DataCenter.tunnelType)}`}/>
                    {props.index == 0 ?<SubInfoItem title={"调光模式:"} value={`${props.lightMode}`}/> : null}
                </View>
                <View style={{flex:1, }}>
                    <SubInfoItem title={"服务器地址:"} value={`${DataCenter.serverIp}`}/>
                    <SubInfoItem title={"设备编号:"} value={`${props.data.gateId ? props.data.gateId : ""}`}/>
                    <SubInfoItem title={"版本号:"} value={`${DeviceInfo.getVersion()}`}/>
                </View>
            </View>
            <View style={{alignItems:'center',flexDirection:'row', justifyContent:'center'}}>
            {props.index == 0 ? <Button
                buttonStyle={{paddingVertical:0, marginTop:scaleSize(54), width:scaleSize(286), height:scaleSize(62), backgroundColor: Colors.second_button_color}} 
                titleStyle={{color:Colors.text1_color, fontSize:FontSize.h4_font}}
                title="升级检查"
                onPress={async ()=>{
                    LoadingUtil.showLoading();
                    try{
                        let netInfoState = await NetInfo.fetch();
                        if(netInfoState.isConnected) {
                            const{success, data} = await getAppVersion();
                            LoadingUtil.dismissLoading();
                            if(success) {
                                if(versionCompare(DeviceInfo.getBuildNumber(), data.ver) >= 0) {
                                    ToastAndroid.show("当前版本是最新版本", ToastAndroid.SHORT);
                                } else {
                                    await UpgradeLibrary.doNewVersionUpdate(data.url, true);
                                }
                            } else {
                                ToastAndroid.show("服务器开小差了，请稍候再试", ToastAndroid.SHORT);
                            }
                        } else {
                            LoadingUtil.dismissLoading();
                            ToastAndroid.show("当前无网络连接", ToastAndroid.SHORT);
                        }
                    }catch(error) {
                        LoadingUtil.dismissLoading();
                    }finally {
                        LoadingUtil.dismissLoading();
                    }
                }}
                /> : null}
                {props.index == 0 ? <Button
                buttonStyle={{marginLeft: scaleSize(20), paddingVertical:0, marginTop: scaleSize(54),width:scaleSize(340), height:scaleSize(62), backgroundColor: Colors.button_color}}
                titleStyle={{fontSize: FontSize.h4_font}}
                title="更改调光模式"
                onPress={async ()=>{
                    let lightMode = SerialPortManager.getLightMode();
                    if(lightMode.value == LightMode.POSITIVE_MODE.value){
                        lightMode = LightMode.NEGATIVE_MODE;
                    } else if(lightMode.value == LightMode.NEGATIVE_MODE.value){
                        lightMode = LightMode.POSITIVE_MODE;
                    }
                    Alert.alert("修改调光模式", "确定将灯具调光模式改为" + lightMode.desc, [
                        {
                            text: "取消",
                            onPress: () => {console.log("canceled")}
                          },
                          { text: "确定", onPress: async() => {
                            UICommandExecute.onSetLightMode(lightMode.value);
                            props.setLight(lightMode.name);
                            // this.setState({lightMode: lightMode.name});
                          }}
                    ]);
                }}
                /> : null}
            </View>
        </View>
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        backgroundColor: Colors.page_bg_color1, 
        justifyContent:'space-around'
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
    cardContainer:{
        flexDirection:'row',
        backgroundColor: Colors.white,
        height:scaleSize(500),
        paddingTop:scaleSize(60),
        paddingHorizontal:scaleSize(100),
    },
    tipContainer: {
        flexDirection:'row',
        paddingVertical: scaleSize(10),
        height:scaleSize(90)
    }
});